//
//  LeaderViewController.m
//  HeartOfMeet
//
//  Created by qianfeng on 16/3/30.
//  Copyright © 2016年 千云锋. All rights reserved.
//

#import "LeaderViewController.h"
#import "TopicModel.h"
#import "LeaderTableViewCell.h"
#import "TopicListViewViewController.h"

@interface LeaderViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>

@end

@implementation LeaderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createAf];
    
    [self createTableView];
    [self createRefreshView];
    [self downLoadDataWithUrl:LEADERURL];
}


- (void)createAf{
    self.manager = [AFHTTPRequestOperationManager manager];
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    self.dataArray = [[NSMutableArray alloc] init];
   
    self.hotfmArray = [[NSMutableArray alloc] init];
    self.newfmArray = [[NSMutableArray alloc] init];
    self.newlessonArray = [[NSMutableArray alloc] init];
    self.dianTaiArray = [[NSMutableArray alloc] init];
}

#pragma mark - tableView创建
- (void)createTableView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-64-49) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.bounces = NO;
    self.tableView.backgroundColor = [UIColor blackColor];
    self.tableView.showsVerticalScrollIndicator = NO;
   [self.tableView registerNib:[UINib nibWithNibName:@"LeaderTableViewCell" bundle:nil] forCellReuseIdentifier:@"LeaderCell"];
    [self.view addSubview:self.tableView];
}

#pragma mark - 创建刷新以及下拉
- (void)createRefreshView  {
    __weak typeof (self) weakSelf = self;
    
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSelf.isRefreshing) {
            return ;
        }
        weakSelf.isRefreshing = YES;
        [weakSelf downLoadDataWithUrl:LEADERURL];
    }];
}

#pragma mark - 结束刷新
- (void)endRefreshing {
    if (self.isRefreshing) {
        self.isRefreshing = NO;
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultNone];
    }
}

#pragma mark - 下载数据
- (void)downLoadDataWithUrl:(NSString *)url{
    [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleShrink];
    [MMProgressHUD showWithTitle:@"请稍后" status:@"Loading..."];
    
    __weak typeof(self)weakSelf = self;
    [weakSelf.manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            NSLog(@"首页网络下载");
            if (self.isRefreshing == YES) {
                [self.dataArray removeAllObjects];
                
                [self.hotfmArray removeAllObjects];
                [self.newfmArray removeAllObjects];
                [self.newlessonArray removeAllObjects];
                [self.dianTaiArray removeAllObjects];
            }
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dataDict = jsonDict[@"data"];
            
            //NSLog(@"%@",self.categoryArray);
            NSArray *hotfmArray = dataDict[@"hotfm"];
            for (NSDictionary *topicDict in hotfmArray) {
                TopicModel *topicModel = [[TopicModel alloc] init];
                [topicModel setValuesForKeysWithDictionary:topicDict];
                
                NSDictionary *diantaiDict = topicDict[@"diantai"];
                [topicModel.dianTaiModel setValuesForKeysWithDictionary:diantaiDict];
                
                NSDictionary *userDict = diantaiDict[@"user"];
                [topicModel.dianTaiModel.userModel setValuesForKeysWithDictionary:userDict];
                [self.hotfmArray addObject:topicModel];
            }
            //NSLog(@"%@",self.hotfmArray);
            NSArray *newfmArray = dataDict[@"newfm"];
            for (NSDictionary *topicDict in newfmArray) {
                TopicModel *topicModel = [[TopicModel alloc] init];
                [topicModel setValuesForKeysWithDictionary:topicDict];
                
                NSDictionary *diantaiDict = topicDict[@"diantai"];
                [topicModel.dianTaiModel setValuesForKeysWithDictionary:diantaiDict];
                
                NSDictionary *userDict = diantaiDict[@"user"];
                [topicModel.dianTaiModel.userModel setValuesForKeysWithDictionary:userDict];
                [self.newfmArray addObject:topicModel];
            }
            //NSLog(@"%@",self.newfmArray);
            NSArray *newlessonArray = dataDict[@"newlesson"];
            for (NSDictionary *topicDict in newlessonArray) {
                TopicModel *topicModel = [[TopicModel alloc] init];
                [topicModel setValuesForKeysWithDictionary:topicDict];
                
                NSDictionary *diantaiDict = topicDict[@"diantai"];
                [topicModel.dianTaiModel setValuesForKeysWithDictionary:diantaiDict];
                
                NSDictionary *userDict = diantaiDict[@"user"];
                [topicModel.dianTaiModel.userModel setValuesForKeysWithDictionary:userDict];
                [self.newlessonArray addObject:topicModel];
            }
            //NSLog(@"%@",self.newlessonArray);
            NSArray *diantaiArray = dataDict[@"diantai"];
            for (NSDictionary *diantaiDict in diantaiArray) {
                DianTaiModel *diantaiModel = [[DianTaiModel alloc] init];
                [diantaiModel setValuesForKeysWithDictionary:diantaiDict];
                
                NSDictionary *userDict = diantaiDict[@"user"];
                [diantaiModel.userModel setValuesForKeysWithDictionary:userDict];
                [self.dianTaiArray addObject:diantaiModel];
            }
            [self.dataArray addObject:self.newfmArray];
            [self.dataArray addObject:self.newlessonArray];
        }
        [self endRefreshing];
        [self subViewSetting];
        [self.tableView reloadData];
        [MMProgressHUD dismissWithSuccess:@"下载完成" title:@"ok"];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"首页下载失败");
    }];
}

#pragma mark - 子视图设置
- (void)subViewSetting{
    [self headerViewSetting];
    [self pageControlSetting];
    [self timerSetting];
}

#pragma mark - headerView设置
- (void)headerViewSetting{
    [self.scrollViewLabel removeFromSuperview];
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.width/2)];
    self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width * self.hotfmArray.count, self.view.bounds.size.width/2);
    self.scrollView.pagingEnabled = YES;
    self.scrollView.bounces = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.delegate = self;
    
    UIImageView *backImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.width/2)];
    backImageView.image = [UIImage imageNamed: @"launch_logo_bg"];
    [self.tableView addSubview:backImageView];
    
    for (int i = 0; i < self.hotfmArray.count; ++i) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width*i, 0, self.view.bounds.size.width, self.view.bounds.size.width/2)];
        imageView.clipsToBounds = YES;
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.tag = 10+i;
        TopicModel *model = self.hotfmArray[i];
        [imageView sd_setImageWithURL:[NSURL URLWithString:model.cover] placeholderImage:[UIImage imageNamed: @"placehold_wide"]];
        //添加手势
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *imageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTap:)];
        [imageView addGestureRecognizer:imageTap];
        
        [self.scrollView addSubview:imageView];
    }
    
    UIImageView *listenImageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, self.scrollView.bounds.size.height-17.5, 15, 15)];
    listenImageView.image = [UIImage imageNamed: @"play2_"];
    [self.tableView addSubview:listenImageView];
    
    self.scrollViewLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, self.scrollView.bounds.size.height-20, self.view.bounds.size.width-25, 20)];
    self.scrollViewLabel.backgroundColor = [UIColor clearColor];
    self.scrollViewLabel.font = [UIFont systemFontOfSize:13];
    self.scrollViewLabel.textColor = [UIColor whiteColor];
    
    [self.tableView addSubview:self.scrollViewLabel];
    TopicModel *model = self.hotfmArray[0];
    self.scrollViewLabel.text = [NSString stringWithFormat:@"  %@",model.title];
    self.tableView.tableHeaderView = self.scrollView;
}

#pragma mark - 滚动视图点击
- (void)imageTap:(UIGestureRecognizer *)imageTap{
    NSLog(@"点击滚动视图播放");
    TopicModel *model = self.hotfmArray[imageTap.view.tag-10];
    
    [PlayerViewController sharePlayer].mainImageUrl = model.cover;
    [PlayerViewController sharePlayer].topicTitle = model.title;
    [PlayerViewController sharePlayer].viewNum = model.viewnum;
    [PlayerViewController sharePlayer].avaImageUrl = model.dianTaiModel.userModel.avatar;
    [PlayerViewController sharePlayer].speakNickName = model.dianTaiModel.userModel.nickname;
    
    [[PlayerViewController sharePlayer] playWithUrl:model.url];
}

#pragma mark - scrollView代理方法
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.timer setFireDate:[NSDate distantFuture]];
//    self.timer = [NSDate distantFuture];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self.timer setFireDate:[NSDate distantPast]];
//    self.timer = [NSDate distantPast];
    NSInteger m = self.scrollView.contentOffset.x / self.scrollView.bounds.size.width;
    self.pageControl.currentPage = m;
    TopicModel *model = self.hotfmArray[m];
    self.scrollViewLabel.text = [NSString stringWithFormat:@"  %@",model.title];
}

#pragma mark - headerView
- (void)pageControlSetting{
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(self.view.bounds.size.width - self.hotfmArray.count * 20, self.scrollView.bounds.size.height-20, self.hotfmArray.count * 20, 20)];
    self.pageControl.numberOfPages = self.hotfmArray.count;
    self.pageControl.userInteractionEnabled = NO;
    
    [self.tableView addSubview:self.pageControl];
}

#pragma mark - 定时器
- (void)timerSetting{
    if (!self.timer) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(update) userInfo:nil repeats:YES];
    }
}

- (void)update{
    static NSInteger m;
    NSInteger n = self.scrollView.contentOffset.x / self.scrollView.bounds.size.width;
    if (n == 0) {
        m = 1;
    }else if (n == self.hotfmArray.count - 1){
        m = -1;
    }
    n += m;
    
    [UIView animateWithDuration:0.5 animations:^{
        self.scrollView.contentOffset = CGPointMake(n * self.scrollView.bounds.size.width, 0);
    } completion:^(BOOL finished) {
        self.pageControl.currentPage = n;
        TopicModel *model = self.hotfmArray[n];
        self.scrollViewLabel.text = [NSString stringWithFormat:@"  %@",model.title];
    }];
}

#pragma mark - 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *arr = self.dataArray[section];
    return arr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}

#pragma mark - 组头设置
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.bounds = CGRectMake(0, 0, self.view.bounds.size.width, 30);
    view.backgroundColor = [UIColor blackColor];
    
    UILabel *sortLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, self.view.bounds.size.width/2, 30)];
    sortLabel.textColor = [UIColor whiteColor];
    sortLabel.font = [UIFont systemFontOfSize:13];
    if (section == 0) {
        sortLabel.text = @"心灵之音  最新FM";
    }else if (section == 1) {
        sortLabel.text = @"心灵之音  心理课程";
    }
    [view addSubview:sortLabel];
    
    UIButton *moreButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.bounds.size.width-80, 0, 80, 30)];
    [moreButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [moreButton setTitle:@"查看更多" forState:UIControlStateNormal];
    moreButton.titleLabel.font = [UIFont systemFontOfSize:13];
    if (section == 0) {
        moreButton.tag = 20;
    }else if (section == 1) {
        moreButton.tag = 21;
    }
    [moreButton addTarget:self action:@selector(moreClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:moreButton];
    
    return view;
}
#pragma mark - 点击更多
- (void)moreClick:(UIButton *)button{
    TopicListViewViewController *topicListVC = [[TopicListViewViewController alloc] init];
    if (button.tag-20 == 0) {
        topicListVC.topicListUrl = NEWFMMOREURL;
        topicListVC.title = @"心灵之音  最新FM";
    }else if (button.tag-20 == 1){
        topicListVC.topicListUrl = NEWLESSONURL;
        topicListVC.title = @"心灵之音  心理课程";
    }
    [self.navigationController pushViewController:topicListVC animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.00000000001;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.bounds = CGRectMake(0, 0, 0, 0.00000000001);
    
    view.backgroundColor = [UIColor colorWithRed:20/255.0 green:20/255.0 blue:20/255.0 alpha:1.0];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 65;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    NSLog(@"jjj:%@",self.newfmArray[indexPath.row]);
    LeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LeaderCell"];
//    cell.contentView.backgroundColor = [UIColor colorWithRed:20/255.0 green:20/255.0 blue:20/255.0 alpha:1.0];
    cell.backgroundColor = [UIColor blackColor];
    

    
    if (indexPath.section == 0) {
        //LeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LeaderCell" forIndexPath:indexPath];
        
        TopicModel *model = self.newfmArray[indexPath.row];
        cell.TitleLabe.text = model.title;
        cell.NameLabel.text = model.speak;
        [cell.CoverImageView sd_setImageWithURL:[NSURL URLWithString:model.cover] placeholderImage:[UIImage imageNamed: @"placehold_rec"]];
        return cell;
    }
    if (indexPath.section == 1) {
//       // LeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LeaderCell"];
        TopicModel *model = self.newlessonArray[indexPath.row];
        cell.TitleLabe.text = model.title;
        cell.NameLabel.text = model.speak;
        [cell.CoverImageView sd_setImageWithURL:[NSURL URLWithString:model.cover] placeholderImage:[UIImage imageNamed: @"placehold_rec"]];
        return cell;
   }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    TopicModel *model = self.dataArray[indexPath.section][indexPath.row];
    
    LeaderTableViewCell *cell = (LeaderTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    CGFloat y = cell.frame.origin.y - tableView.contentOffset.y;
    [LZXHelper animationPlayWithUrl:model.cover viewController:self leaderFrame:CGRectMake(8, y+64+7, 50, 50) newFrame:CGRectMake(self.view.bounds.size.width-30, 30, 6, 6)];
    
    [PlayerViewController sharePlayer].mainImageUrl = model.cover;
    [PlayerViewController sharePlayer].topicTitle = model.title;
    [PlayerViewController sharePlayer].viewNum = model.viewnum;
    [PlayerViewController sharePlayer].avaImageUrl = model.dianTaiModel.userModel.avatar;
    [PlayerViewController sharePlayer].speakNickName = model.dianTaiModel.userModel.nickname;
    
    [[PlayerViewController sharePlayer] playWithUrl:model.url];
}



@end
